package com.eatme.web.app.coupon.template.service.impl;

import com.eatme.web.app.coupon.common.exception.AppException;
import com.eatme.web.app.coupon.common.vo.CouponTemplateSDK;
import com.eatme.web.app.coupon.template.dao.CouponTemplateDao;
import com.eatme.web.app.coupon.template.entity.CouponTemplate;
import com.eatme.web.app.coupon.template.service.ITemplateBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 优惠券模版基础服务接口实现
 */
@Service
public class TemplateBaseServiceimpl implements ITemplateBaseService {

    /** couponTemplateDao */
    private final CouponTemplateDao couponTemplateDao;

    @Autowired
    public TemplateBaseServiceimpl(CouponTemplateDao couponTemplateDao) {
        this.couponTemplateDao = couponTemplateDao;
    }

    @Override
    public CouponTemplate buildTemplateInfo(Integer id) throws AppException {
        Optional<CouponTemplate> template = couponTemplateDao.findById(id);
        if (!template.isPresent()) {
            throw new AppException("Template Is Not Exist:"+id);
        }
        return template.get();
    }

    @Override
    public List<CouponTemplateSDK> findAllUsableTemplate() {
        List<CouponTemplate> templates =
                couponTemplateDao.findAllByAvailableAndExpired(true,false);

        return templates.stream().map(this::couponTemplateToTemplateSDK).collect(Collectors.toList());
    }

    @Override
    public Map<Integer, CouponTemplateSDK> findIds2TemplateSDK(Collection<Integer> ids) {
        List<CouponTemplate> templates =couponTemplateDao.findAllById(ids);

        return templates.stream().map(this::couponTemplateToTemplateSDK).collect(Collectors.toMap(CouponTemplateSDK::getId, Function.identity()));
    }


    private CouponTemplateSDK couponTemplateToTemplateSDK(CouponTemplate template){
        return new CouponTemplateSDK(
                template.getId(),
                template.getName(),
                template.getLogo(),
                template.getDesc(),
                template.getCategory().getCode(),
                template.getProductLine().getCode(),
                template.getKey(), // 并不是拼装好的Template key
                template.getTarget().getCode(),
                template.getRule()
                );
    }
}
